package com.rich.dmr.widget;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.provider.Settings;
import java.math.BigDecimal;
import java.util.Objects;

import rich.dmr.DmrManager;

public class DmrDisplayProvider extends AppWidgetProvider {
    private final String TAG = "dmr---DmrDisplayProvider";
    private DmrManager dmrManager;
    private final static String EXTRA_RESPONSE_DATA = "com.android.extra.RESPONSE_DATA";
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    @Override
    public void onEnabled(final Context context) {
        super.onEnabled(context);
    }

    @SuppressLint("WrongConstant")
    private void updateView(Context context,Intent intent) {
        dmrManager = (DmrManager) context.getSystemService("dmrservice");
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.widget_dmr_display);
        final Intent showDmr = new Intent(MainActivity.ACTION_SHOW_DMR);
        final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, showDmr, 0);
        remoteViews.setOnClickPendingIntent(R.id.dmr_appwidget, pendingIntent);
        switch (Objects.requireNonNull(intent.getAction())) {
            case "android.intent.action.MODULE_STATE":
                int moduleState = intent.getIntExtra(EXTRA_RESPONSE_DATA, -1);
                if (moduleState == 1) {
                    //dmrManager.getDigitalVoiceInfo();
                } else if (moduleState == 2) {
                    setRemoteViewNormal(remoteViews,context);
                } else if (moduleState == 3) {

                } else if (moduleState == 4) {
                    setRemoteViewNormal(remoteViews,context);

                } else if (moduleState == 5) {
                    dmrManager.getSms();
                }
                break;
            case "android.intent.action.INCOMING_CALL_STATE":
                //setRemoteViewIncoming(remoteViews,intent,context);
                break;
            case "android.intent.action.DIGITAL_MODE_SET":
            case "android.appwidget.action.APPWIDGET_UPDATE":
                setRemoteViewNormal(remoteViews,context);
                break;
            default:
                break;
        }

        AppWidgetManager widgetManager = AppWidgetManager
                .getInstance(context.getApplicationContext());
        ComponentName componentName = new ComponentName(context.getApplicationContext(),
                DmrDisplayProvider.class);
        widgetManager.updateAppWidget(componentName, remoteViews);
    }

    public void setRemoteViewNormal(RemoteViews remoteViews,Context context){
        remoteViews.setTextViewText(R.id.tv_dmr_mode, dmrManager.getMode() == 0 ? "DMR":"POC");
        String power = dmrManager.getPower()==1 ? "(H)":"(L)";
        String channelName = Settings.System.getString(context.getContentResolver(),"channel_name");
        remoteViews.setTextViewText(R.id.tv_frequency, channelName != null ? channelName + power :"Channel1(H)");
        remoteViews.setTextViewText(R.id.tv_contact, findContactName(context));
        String zoneName = Settings.System.getString(context.getContentResolver(),"channel_zone");
        //remoteViews.setTextViewText(R.id.tv_local_id, "Local ID: " + String.valueOf(dmrManager.getLocalId()));
        remoteViews.setTextViewText(R.id.tv_local_id, zoneName);

    }

    public void setRemoteViewIncoming(RemoteViews remoteViews,Intent intent,Context context){
        int callType = intent.getIntExtra("call_type", -1);
        int localId = intent.getIntExtra("local_id", -1);
        int incomingContact = intent.getIntExtra("incoming_contact", -1);
        remoteViews.setTextViewText(R.id.tv_frequency, findChannelName(context));
        if (callType == 1) {
            remoteViews.setTextViewText(R.id.tv_contact, "Group: " + String.valueOf(incomingContact));
        } else if (callType == 0) {
            remoteViews.setTextViewText(R.id.tv_contact, "Single: " + String.valueOf(incomingContact));
        } else {
            remoteViews.setTextViewText(R.id.tv_contact, "All: " + String.valueOf(incomingContact));
        }
        remoteViews.setTextViewText(R.id.tv_local_id, "Caller ID: " + String.valueOf(localId));
    }

    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
    }

    @SuppressLint("LongLogTag")
    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        Log.d(TAG, "action=" + intent.getAction());
        updateView(context,intent);
    }

    private String findChannelName(Context context){
        String zoneName = Settings.System.getString(context.getContentResolver(),"channel_zone");
        if(zoneName == null || zoneName.equals("")){
            zoneName = "none";
        }
        ChannelModel channelModel = DataBaseUtils.getInstance(context).
                findChannel(dmrManager.getTransmitFrequency(),dmrManager.getReceiveFrequency(),
                        dmrManager.getColorCode(),dmrManager.getInboundSlot(),dmrManager.getPower(),
                        dmrManager.getChannelMode(),zoneName,(int)dmrManager.getEncryptKey());
        return channelModel != null ? channelModel.getNameChannel()+"("+(channelModel.getPower() == 1 ? "H" : "L" )+")" : "Channel1(H)";
    }

    private String findContactName(Context context){
        String contactName = DataBaseUtils.getInstance(context).findContactByPhone(dmrManager.getTransmitContact(),dmrManager.getContactType());
        return contactName != null ? contactName: String.valueOf(dmrManager.getTransmitContact());
    }

    private static String removeLastZero(int fre) {
        StringBuffer freString = new StringBuffer(String.valueOf(div(fre, 1000000))).reverse();
        StringBuilder buff = new StringBuilder();
        boolean isFirstNum = false;
        for (int i = 0; i < freString.length(); i++) {
            char c = freString.charAt(i);
            if (!isFirstNum && c != '0') {
                if(c == '.'){
                    continue;
                }
                isFirstNum = true;
            }

            if (isFirstNum ) {
                buff.append(c);
            }
        }
        return buff.reverse().toString() + "MHZ";
    }

    public static BigDecimal div(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, 4, BigDecimal.ROUND_HALF_UP);
    }
}
